package fischl.web;

import fi.iki.elonen.NanoHTTPD;
import fischl.DanmuUtil;
import fischl.Global;
import fischl.Platform;
import fischl.douyuApi.model.Danmu;
import fischl.log.Log;
import fischl.log.LogFactory;
import fischl.model.DanmuGroup;
import fischl.model.VideoModel;
import fischl.model.Room;

import static fi.iki.elonen.NanoHTTPD.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DanmuHandler implements RouteHandler {
  private static final Log log = LogFactory.get("danmuRoute");

  @Override
  public NanoHTTPD.Response handle(NanoHTTPD.IHTTPSession session) {
    if(!"/danmu".equals(session.getUri())) return null;
    String vid = session.getParms().get("vid");

    Map<String, Object> model = new HashMap<>();
    final VideoModel video = Platform.current().getVideoModelByVid(vid);
    if (video != null) {
      model.put("docTitle", video.title);
      model.put("title", video.title);
      model.put("upId", video.upId);
      model.put("upName", video.upName);
      model.put("liveRoom", "https://www.douyu.com/" + Room.getByUpId(video.upId).roomId);
    }

    List<Danmu> list = Platform.current().getDanmu(vid);
    int totalCount = list.size();
    log.i("find {} danmu for vid {}", totalCount, vid);

    int duplicatedCount;
    List<DanmuGroup> groups;
    if (totalCount > 0) {
      duplicatedCount = DanmuUtil.removeDuplicatedDanmus(list, 10/*seconds*/);
      groups = DanmuUtil.findTopMinuteGroups(list, 15);
    } else {
      duplicatedCount = 0;
      groups = Collections.emptyList();
    }

    model.put("totalCount", totalCount);
    model.put("duplicateCount", duplicatedCount);
    model.put("videoId", vid);
    model.put("groups", Global.gson().toJson(groups));
    model.put("videoPage", video == null ? "": video.videoUrl);
    String result = TemplateEngine.render("danmu.ftlh", model);
    return newFixedLengthResponse(Response.Status.OK, "text/html", result);
  }
}
